package com.xbongbong.saas.help.workflow;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.ConfigConstant;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.errorcodes.PaymentErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.product.pojo.ProductSavePojo;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.help.SaasProductHelp;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author 魏荣杰
 *
 */
@Component
public class PurchaseHelp {

    private static final Logger LOG = LoggerFactory.getLogger(PurchaseHelp.class);

    @Resource
    private PurchaseProductModel purchaseProductModel;
    @Resource
    private SaasProductHelp saasProductHelp;
    @Resource
    private PurchaseModel purchaseModel;


    public boolean judgePurchaseAllInBound(Long instockId, Long purchaseId, String corpid, List<ProductSavePojo> productSavePojoList) throws XbbException {
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("purchaseSheetId", purchaseId);
        param.put("del", 0);
        // 拿到合同的所有产品
        List<PurchaseProductEntity> purchaseProductEntityList = purchaseProductModel.findEntitys(param);

        Map<Long, Double> purchaseNumMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, Double> oldPurchaseNumMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        boolean needMerge = false;
        for (ProductSavePojo productSavePojo : productSavePojoList){
            if (Objects.isNull(productSavePojo.getRefProductId())) {
                needMerge = true;
                break;
            }
        }
        for (ProductSavePojo productSavePojo : productSavePojoList){
            if (Objects.nonNull(productSavePojo.getRefProductId())) {
                Double num = purchaseNumMap.getOrDefault(productSavePojo.getRefProductId(), 0D);
                num  = Arith.add(num,productSavePojo.getNum());
                purchaseNumMap.put(productSavePojo.getRefProductId(), num);
            }else {
                Double num = oldPurchaseNumMap.getOrDefault(productSavePojo.getId(), 0D);
                num = Arith.add(num, productSavePojo.getNum());
                oldPurchaseNumMap.put(productSavePojo.getId(), num);
            }
        }
        List<PurchaseProductEntity> productEntities = new ArrayList<>();
        if (!needMerge){
//            新数据逻辑
            boolean isAllOutBound = true;
            for (PurchaseProductEntity entity : purchaseProductEntityList){
                if (purchaseNumMap.containsKey(entity.getId())) {
                    //剩余未入
//                    Double unStockNum = Arith.sub(entity.getProductNum(),entity.getInstockNum());
                    // 只要有一个入库数量 < 产品总数，就应该是未全部出库
                    //当前入库
                    Double amendNum = purchaseNumMap.get(entity.getId());
                    if (Arith.sub(entity.getProductNum(), Arith.add(entity.getInstockNum(), amendNum)) > 0) {
                        isAllOutBound = false;
                    }
                    entity.setInstockNum(amendNum);
                    productEntities.add(entity);
                }else {
                    //该采购合同产品不再入库单中，采购合同肯定没入完
                    if (Arith.sub(entity.getProductNum(),entity.getInstockNum()) > 0) {
                        isAllOutBound = false;
                    }
                }
            }
            if(!productEntities.isEmpty()){
                purchaseProductModel.updateInstock(productEntities, corpid);
            }
            return isAllOutBound;
        }else {
            //            老数据逻辑
            for (PurchaseProductEntity entity : purchaseProductEntityList){
                Double num = purchaseNumMap.getOrDefault(entity.getProductId(),0D);
                num = Arith.add(num,entity.getProductNum());
                purchaseNumMap.put(entity.getProductId(),num);
                if (oldPurchaseNumMap.containsKey(entity.getProductId())) {
                    // 剩余未入
                    Double unStockNum = Arith.sub(entity.getProductNum(), entity.getInstockNum());
                    Double amendNum = oldPurchaseNumMap.get(entity.getProductId());
                    Double instockNum;
                    Double inNum = Arith.sub(amendNum, unStockNum);
                    if (inNum > 0) {
                        instockNum = entity.getProductNum();
                        oldPurchaseNumMap.put(entity.getProductId(), inNum);
                    }else {
                        instockNum = Arith.add(entity.getInstockNum(), amendNum);
                        oldPurchaseNumMap.remove(entity.getProductId());
                    }
                    entity.setUpdateTime(DateTimeUtil.getInt());
                    entity.setInstockNum(instockNum);
                    productEntities.add(entity);
                }
            }
            if(!productEntities.isEmpty()){
                purchaseProductModel.updateBatch(productEntities,corpid);
            }
            return saasProductHelp.judgeAllInBound(purchaseNumMap,purchaseId, InstockTypeEnum.PURCHASE_INSTOCK.getCode(),corpid,productSavePojoList,instockId);
        }
    }

    /**
     * 判断已付金额是否已经超过采购合同内的未付金额
     *
     * @param sheetTypeEnum
     * @param corpid
     * @param contractIdToAmount
     * @param contractIds
     */
    public void checkContract(SheetTypeEnum sheetTypeEnum, String corpid, Map<Long, Double> contractIdToAmount, Set<Long> contractIds) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("idIn", contractIds);
        List<PurchaseEntityExt> contracts = purchaseModel.findEntitys(param);
        if (Objects.isNull(contracts)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        boolean isRedFlag = SheetTypeEnum.isRed(sheetTypeEnum);
        boolean isBadFlag = SheetTypeEnum.isBad(sheetTypeEnum);
        for (PurchaseEntityExt contractEntityExt : contracts) {
            String name = contractEntityExt.getSerialNo();
            if (Objects.equals(contractEntityExt.getDel(), DelEnum.DELETE.getDel())) {
                throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208032, PaymentErrorCodeEnum.API_ERROR_208032.getMsg(), XbbRefTypeEnum.PURCHASE.getName(), name);
            }
            Long contractId = contractEntityExt.getId();
            Double value = contractIdToAmount.getOrDefault(contractId, 0D);
            if (value == 0) {
                continue;
            }
            Double tempAmount = value;
            if (isRedFlag) {
                //红冲的，先把红冲金额取正数，然后判断红冲金额是否小于已收
                tempAmount = Math.abs(value);
            }
            JSONObject data = contractEntityExt.getData();
            Double finishMoney = FastJsonHelper.getDoubleOrDefaultFromFormData(data, PurchaseEnum.FINISH_AMOUNT.getAttr(), 0D);
            Double unAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(data, PurchaseEnum.UN_FINISH_AMOUNT.getAttr(), 0D);
            //校验填充的金额是否超过合同的已收/未收（根据是否红冲判断不同）
            if (isRedFlag) {
                //红冲，限制红冲金额tempAmount小于等于合同已收金额finishMoney
                if (Arith.sub(tempAmount , finishMoney) > ConfigConstant.amountAccuracy) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.DETAIL_BEYOND_AMOUNT_RED, XbbRefTypeEnum.PURCHASE.getName() + name);
                }
            } else if (Arith.sub(value , unAmount) > ConfigConstant.amountAccuracy) {
                //普通回款、坏账，限制回款金额小于等于合同未收金额
                String msg = I18nMessageUtil.getMessage(ErrorMessageConstant.DETAIL_BEYOND_AMOUNT_PAY);
                if (isBadFlag) {
                    msg = I18nMessageUtil.getMessage(ErrorMessageConstant.DETAIL_BEYOND_AMOUNT_BAD);
                }
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, String.format(msg, XbbRefTypeEnum.PURCHASE.getName(), name));
            }
        }
    }

    /**
     * 处理付款计划并封装要更新的结果：并把付款计划的已付金额增加及更改其付款状态等
     *
     * @param sheetTypeEnum
     * @param corpid
     * @param contractIdToAmount
     * @param contractIds
     * @return
     */
    public List<UpdateDataEntity> handleContract(SheetTypeEnum sheetTypeEnum, String corpid, Map<Long, Double> contractIdToAmount, Set<Long> contractIds) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("idIn", contractIds);
        List<PurchaseEntityExt> contracts = purchaseModel.findEntitys(param);
        boolean isRedFlag = SheetTypeEnum.isRed(sheetTypeEnum);
        boolean isBadFlag = SheetTypeEnum.isBad(sheetTypeEnum);
        List<UpdateDataEntity> updateList = new ArrayList<>();
        for (PurchaseEntityExt contractEntityExt : contracts) {
            Long contractId = contractEntityExt.getId();
            Double value = contractIdToAmount.getOrDefault(contractId, 0D);
            if (value == 0) {
                continue;
            }
            JSONObject data = contractEntityExt.getData();
            Double finishMoney = FastJsonHelper.getDoubleOrDefaultFromFormData(data, PurchaseEnum.FINISH_AMOUNT.getAttr(), 0D);
            if (isRedFlag) {
                //红冲的，把金额置为负数。用tempAmount计算金额是否合法
                value = Arith.mul(value, -1);
            }
            JSONObject updateData = new JSONObject();
            /*
             处理采购合同的已收未收
             （1）采购合同此次只增加实付金额、未付金额、收款比例
             （2）毛利、毛利率、成本这些是没有的（销售合同才会存在这种说法，采购合同是我们花钱去买东西，花出去的采购金额，都相当于企业付出的成本）- 凤娇
             */
            Double badAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(data, PurchaseEnum.BAD_AMOUNT.getAttr(), 0D);
            if (isBadFlag) {
                /*
                 坏账时：已收不变，合同总额不变，未收减少，坏账增加，收款比例不变（= 已收/总合同额）
                 */
                Double oldUnFinishMoney = FastJsonHelper.getDoubleOrDefaultFromFormData(data, PurchaseEnum.UN_FINISH_AMOUNT.getAttr(), 0D);
                Double newUnFinishMoney = Arith.sub(oldUnFinishMoney, value);
                //坏账增加
                Double newBadAmount = Arith.add(badAmount, value);
                updateData.put(PurchaseEnum.UN_FINISH_AMOUNT.getAttr(), newUnFinishMoney);
                updateData.put(PurchaseEnum.BAD_AMOUNT.getAttr(), newBadAmount);
            } else {
                /*
                 普通、红冲回款时（红冲是负值，所以可以和普通回款一样处理方式）：已收增加，合同总额不变，未收减少，坏账不变-收款比例增加（= 已收/总合同额）
                 */
                Double amount = FastJsonHelper.getDoubleOrDefaultFromFormData(data, PurchaseEnum.TOTAL_MONEY.getAttr(), 0D);
                //此处直接add没问题：红冲时value是负数
                //注：为防止与原逻辑不一致，此处来回加减的代码参照旧代码内对各种金额的处理
                Double newFinishMoney = Arith.add(finishMoney, value);
                //合同未收 = 合同金额 - 合同已收 - 合同坏账
                Double newUnFinishMoney = Arith.sub(amount, newFinishMoney);
                newUnFinishMoney = Arith.sub(newUnFinishMoney, badAmount);
                updateData.put(PurchaseEnum.FINISH_AMOUNT.getAttr(), newFinishMoney);
                updateData.put(PurchaseEnum.UN_FINISH_AMOUNT.getAttr(), newUnFinishMoney);
                FastJsonHelper.handleAttrPercent(updateData, newFinishMoney, amount, PurchaseEnum.RECEINE_PERCENT.getAttr());
            }
            UpdateDataEntity updateDataEntity = ExplainUtil.getUpdateData(contractId, updateData, corpid);
            updateList.add(updateDataEntity);
        }
        return updateList;
    }

    /**
     * 新建付款单时，同步更新采购合同
     * @param corpid 公司id
     * @param updateList 要更新的采购合同list
     * @param errorMsg 错误信息
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public void savePurchase(String corpid, List<UpdateDataEntity> updateList, String errorMsg) throws XbbException {
        try {
            if (updateList.size() > 0) {
                purchaseModel.updateBatch(updateList, corpid);
            }
        } catch (Exception e) {
            LOG.error(errorMsg, e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
